#include <GL/gl.h>

#include "Class/Manager/Graphics.hpp"

namespace		Manager
{
  bool			Graphics::GetEvent(sf::Event &event) throw()
  {
	if (this->IsOpened())
	  if (this->_Window->GetEvent(event))
		{
		  if (event.Type == sf::Event::Closed)
			this->Close();
		  else if (event.Type == sf::Event::KeyPressed
				   && event.Key.Code == sf::Key::Escape)
			this->Close();
		  return (true);
		}
	return (false);
  }
  float			Graphics::GetFrameTime() const throw()
  {
	if (!this->IsOpened())
	  return (.0f);
	return (this->_Window->GetFrameTime());
  }

  void			Graphics::SetBackgroundColor(char unsigned r, char unsigned g, char unsigned b)
  {
	this->_Color = sf::Color(r, g, b);
  }

  bool			Graphics::SetConfiguration(Configuration const &c)
  {
	int unsigned	i = 0, count = sf::VideoMode::GetModesCount();

	for ( ; i < count ; ++i)
	  {
		sf::VideoMode	mode = sf::VideoMode::GetMode(i);

		if (mode.Width == c.Width() && mode.Height == c.Height())
		  break ;
	  }

	if (i != count)
	  {
		this->_Config = c;
		return (true);
	  }
	return (false);
  }
  bool			Graphics::SetDefaultConfiguration()
  {
	this->_Config = Configuration();

	return (true);
  }


  void			Graphics::SetDefaultGUICamera()
  {
	this->SetCamera(Entity::Camera2D(Component::Vector3f(this->_Config.Width() / 2.f, this->_Config.Height() / 2.f, .0f),
									 Component::Vector2i(this->_Config.Width(), this->_Config.Height())));
  }

  void			Graphics::SetDefault2DCamera()
  {
	this->SetCamera(Entity::Camera2D(Component::Vector3f(.0f, .0f, .0f),
									 Component::Vector2i(this->_Config.Width(), this->_Config.Height())));
  }

  void			Graphics::SetDefault3DCamera()
  {
	this->SetCamera(Entity::Camera3D(Component::Vector3f(.0f, .0f, -100.f),
									 Component::Vector3f(.0f, .0f, .0f)));
  }

  void			Graphics::SetCamera(Entity::Camera2D const &c)
  {
	static sf::View		view;

	view.SetCenter(c.GetPosition().x, c.GetPosition().y);
	view.SetHalfSize(c.GetRectangle().x / 2, c.GetRectangle().y / 2);
	this->_Window->SetView(view);
  }

  void			Graphics::SetCamera(Entity::Camera3D const &c)
  {
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	gluPerspective(70.f, static_cast<float>(this->_Config.Width()) / static_cast<float>(this->_Config.Height()), .1f, 200.f);


	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	Component::Vector3f const	&pos = c.GetPosition(), &target = c.GetTarget();
	gluLookAt(pos.x, pos.y, pos.z, target.x, target.y, target.z, .0f, -1.f, .0f);
  }
}
